<template>
  <div class="aps-section">
    <el-row>
      <span style="font-weight: 600; margin-top: 1px; font-size: large; color: rgb(1, 128, 165);">
        上班时段初始化
      </span>
      <!-- 右侧浮动的按钮 -->
      <el-button type="text" style="float: right;" @click="toggleDisplay">
        {{ showWorkTime ? '收起' : '展开' }}
      </el-button>
    </el-row>
    
    <transition name="slide-toggle">
      <div v-show="showWorkTime" style="margin-top: 20px;">
        <!-- 工作时段表格 -->
        <el-table
          :data="workTimeData"
          :default-expand-all="false"
          style="width: 100%"
          class="work-time-table"
          row-key="day"
        >
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template #default="{ row, $index }">
              <div class="expand-content">
                <!-- 生产时段配置 -->
                <div class="time-section">
                  <div class="section-header">
                    <span class="section-title">生产时段</span>
                    <el-button type="primary" size="small" class="idoo-details-button" 
                      @click="addWorkPeriod($index)">
                      + 添加时段
                    </el-button>
                  </div>
                  
                  <div v-if="row.workPeriods.length === 0" class="empty-state">
                    暂无生产时段配置
                  </div>
                  
                  <div v-for="(period, periodIndex) in row.workPeriods" 
                    :key="periodIndex" class="time-period-item">
                    <div class="time-period-row">
                      <el-time-picker
                        v-model="period.startTime"
                        placeholder="开始时间"
                        format="HH:mm"
                        value-format="HH:mm"
                        size="small"
                        style="margin-right: 10px;"
                        @change="validateWorkTime($index, periodIndex)"
                      />
                      <span style="margin: 0 5px;">至</span>
                      <el-time-picker
                        v-model="period.endTime"
                        placeholder="结束时间"
                        format="HH:mm"
                        value-format="HH:mm"
                        size="small"
                        style="margin-right: 10px;"
                        @change="validateWorkTime($index, periodIndex)"
                      />
                      <el-button type="text" size="small" class="delete-icon-button"
                        @click="removeWorkPeriod($index, periodIndex)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                    <div v-if="period.error" class="error-text">
                      {{ period.error }}
                    </div>
                  </div>
                </div>
                
                <!-- 加班时段配置 -->
                <div class="time-section" style="margin-top: 20px;">
                  <div class="section-header">
                    <span class="section-title">加班时段</span>
                    <el-button v-if="!row.overtimePeriod" type="primary" size="small" 
                      class="idoo-details-button" @click="addOvertimePeriod($index)">
                      + 增加加班时段
                    </el-button>
                  </div>
                  
                  <div v-if="!row.overtimePeriod" class="empty-state">
                    暂无加班时段配置
                  </div>
                  
                  <div v-if="row.overtimePeriod" class="time-period-item">
                    <div class="time-period-row">
                      <el-time-picker
                        v-model="row.overtimePeriod.startTime"
                        placeholder="开始时间"
                        format="HH:mm"
                        value-format="HH:mm"
                        size="small"
                        style="margin-right: 10px;"
                        @change="validateOvertimeTime($index)"
                      />
                      <span style="margin: 0 5px;">至</span>
                      <el-time-picker
                        v-model="row.overtimePeriod.endTime"
                        placeholder="结束时间"
                        format="HH:mm"
                        value-format="HH:mm"
                        size="small"
                        style="margin-right: 10px;"
                        @change="validateOvertimeTime($index)"
                      />
                      <el-button type="text" size="small" class="delete-icon-button"
                        @click="removeOvertimePeriod($index)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                    <div v-if="row.overtimePeriod.error" class="error-text">
                      {{ row.overtimePeriod.error }}
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <!-- 星期列 -->
          <el-table-column prop="dayName" label="星期" width="120" />
          
          <!-- 生产时段列 -->
          <el-table-column label="生产时段" min-width="200">
            <template #default="{ row }">
              <div v-if="row.workPeriods.length > 0">
                <el-tag 
                  v-for="(period, index) in row.workPeriods" 
                  :key="index" 
                  size="small" 
                  style="margin: 2px;"
                >
                  {{ period.startTime }} - {{ period.endTime }}
                </el-tag>
              </div>
              <span v-else class="empty-text">暂无配置</span>
            </template>
          </el-table-column>
          
          <!-- 加班时段列 -->
          <el-table-column label="加班时段" min-width="150">
            <template #default="{ row }">
              <el-tag v-if="row.overtimePeriod" size="small" type="warning">
                {{ row.overtimePeriod.startTime }} - {{ row.overtimePeriod.endTime }}
              </el-tag>
              <span v-else class="empty-text">暂无配置</span>
            </template>
          </el-table-column>
          
        </el-table>
      </div>
    </transition>

  </div>
</template>

<script>
import { ref, reactive, defineComponent } from 'vue'
import { Delete } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'WorkTimeConfig',
  components: {
    Delete
  },
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    collapsed: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'update:collapsed'],
  setup(props, { emit }) {
    // 控制显示隐藏
    const showWorkTime = ref(!props.collapsed)
    
    // 默认工作时段数据
    const getDefaultWorkTimeData = () => [
      {
        day: 1,
        dayName: '星期一',
        expanded: false,
        workPeriods: [
          { startTime: '08:00', endTime: '12:00', error: '' },
          { startTime: '13:00', endTime: '17:00', error: '' }
        ],
        overtimePeriod: null
      },
      {
        day: 2,
        dayName: '星期二',
        expanded: false,
        workPeriods: [
          { startTime: '08:00', endTime: '12:00', error: '' },
          { startTime: '13:00', endTime: '17:00', error: '' }
        ],
        overtimePeriod: null
      },
      {
        day: 3,
        dayName: '星期三',
        expanded: false,
        workPeriods: [
          { startTime: '08:00', endTime: '12:00', error: '' },
          { startTime: '13:00', endTime: '17:00', error: '' }
        ],
        overtimePeriod: null
      },
      {
        day: 4,
        dayName: '星期四',
        expanded: false,
        workPeriods: [
          { startTime: '08:00', endTime: '12:00', error: '' },
          { startTime: '13:00', endTime: '17:00', error: '' }
        ],
        overtimePeriod: null
      },
      {
        day: 5,
        dayName: '星期五',
        expanded: false,
        workPeriods: [
          { startTime: '08:00', endTime: '12:00', error: '' },
          { startTime: '13:00', endTime: '17:00', error: '' }
        ],
        overtimePeriod: null
      },
      {
        day: 6,
        dayName: '星期六',
        expanded: false,
        workPeriods: [],
        overtimePeriod: null
      },
      {
        day: 0,
        dayName: '星期日',
        expanded: false,
        workPeriods: [],
        overtimePeriod: null
      }
    ]
    
    // 工作时段数据
    const workTimeData = reactive(props.modelValue.length > 0 ? props.modelValue : getDefaultWorkTimeData())


    // 切换显示状态
    const toggleDisplay = () => {
      showWorkTime.value = !showWorkTime.value
      emit('update:collapsed', !showWorkTime.value)
    }

    // 切换某一天的展开状态
    const toggleDayExpand = (dayIndex) => {
      workTimeData[dayIndex].expanded = !workTimeData[dayIndex].expanded
      updateData()
    }

    // 添加生产时段
    const addWorkPeriod = (dayIndex) => {
      workTimeData[dayIndex].workPeriods.push({
        startTime: '',
        endTime: '',
        error: ''
      })
      updateData()
    }

    // 删除生产时段
    const removeWorkPeriod = (dayIndex, periodIndex) => {
      workTimeData[dayIndex].workPeriods.splice(periodIndex, 1)
      updateData()
    }

    // 添加加班时段
    const addOvertimePeriod = (dayIndex) => {
      workTimeData[dayIndex].overtimePeriod = {
        startTime: '',
        endTime: '',
        error: ''
      }
      updateData()
    }

    // 删除加班时段
    const removeOvertimePeriod = (dayIndex) => {
      workTimeData[dayIndex].overtimePeriod = null
      updateData()
    }

    // 验证时间范围是否重复
    const isTimeOverlap = (periods, currentIndex) => {
      const current = periods[currentIndex]
      if (!current.startTime || !current.endTime) return false

      for (let i = 0; i < periods.length; i++) {
        if (i === currentIndex) continue
        const other = periods[i]
        if (!other.startTime || !other.endTime) continue

        // 检查时间重叠
        if (
          (current.startTime < other.endTime && current.endTime > other.startTime)
        ) {
          return true
        }
      }
      return false
    }

    // 验证生产时段
    const validateWorkTime = (dayIndex, periodIndex) => {
      const period = workTimeData[dayIndex].workPeriods[periodIndex]
      period.error = ''

      // 检查开始时间是否小于结束时间
      if (period.startTime && period.endTime && period.startTime >= period.endTime) {
        period.error = '开始时间必须小于结束时间'
        updateData()
        return
      }

      // 检查是否与其他时段重复
      if (isTimeOverlap(workTimeData[dayIndex].workPeriods, periodIndex)) {
        period.error = '时间段不能重复'
        updateData()
        return
      }
      
      updateData()
    }

    // 验证加班时段
    const validateOvertimeTime = (dayIndex) => {
      const overtime = workTimeData[dayIndex].overtimePeriod
      if (!overtime) return

      overtime.error = ''

      // 检查开始时间是否小于结束时间
      if (overtime.startTime && overtime.endTime && overtime.startTime >= overtime.endTime) {
        overtime.error = '开始时间必须小于结束时间'
        updateData()
        return
      }

      // 检查是否与生产时段重复
      const workPeriods = workTimeData[dayIndex].workPeriods
      for (const period of workPeriods) {
        if (!period.startTime || !period.endTime) continue
        if (
          (overtime.startTime < period.endTime && overtime.endTime > period.startTime)
        ) {
          overtime.error = '加班时段不能与生产时段重复'
          updateData()
          return
        }
      }
      
      updateData()
    }

    // 更新数据到父组件
    const updateData = () => {
      emit('update:modelValue', JSON.parse(JSON.stringify(workTimeData)))
    }

    // 获取表单数据
    const getFormData = () => {
      return JSON.parse(JSON.stringify(workTimeData))
    }

    // 加载数据
    const loadData = (data) => {
      if (data && data.length > 0) {
        Object.assign(workTimeData, data)
      } else {
        Object.assign(workTimeData, getDefaultWorkTimeData())
      }
    }

    // 验证所有时段配置
    const validateForm = () => {
      const errors = []
      
      workTimeData.forEach((dayConfig, dayIndex) => {
        // 验证生产时段
        dayConfig.workPeriods.forEach((period, periodIndex) => {
          if (period.error) {
            errors.push(`${dayConfig.dayName} 生产时段 ${periodIndex + 1}: ${period.error}`)
          }
        })
        
        // 验证加班时段
        if (dayConfig.overtimePeriod && dayConfig.overtimePeriod.error) {
          errors.push(`${dayConfig.dayName} 加班时段: ${dayConfig.overtimePeriod.error}`)
        }
      })
      
      return {
        valid: errors.length === 0,
        errors
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(workTimeData, getDefaultWorkTimeData())
      updateData()
    }


    // 暴露方法给父组件
    const exposed = {
      getFormData,
      loadData,
      validateForm,
      resetForm,
      toggleDisplay
    }

    return {
      showWorkTime,
      workTimeData,
      toggleDisplay,
      toggleDayExpand,
      addWorkPeriod,
      removeWorkPeriod,
      addOvertimePeriod,
      removeOvertimePeriod,
      validateWorkTime,
      validateOvertimeTime,
      updateData,
      ...exposed
    }
  }
})
</script>

<style scoped>
.aps-section {
  background-color: #ebebeb;
  padding: 15px;
  margin-top: 20px;
  border-radius: 5px;
}

.slide-toggle-enter-active,
.slide-toggle-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-toggle-enter,
.slide-toggle-leave-to {
  max-height: 0;
  opacity: 0;
}

.slide-toggle-enter {
  max-height: 0;
}

.slide-toggle-leave-to {
  max-height: 0;
}

/* 上班时段初始化样式 */
.day-config-item {
  margin-bottom: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  cursor: pointer;
  transition: background-color 0.2s;
}

.day-header:hover {
  background-color: #f0f0f0;
}

.day-title {
  font-weight: 600;
  color: #714B67;
  font-size: 14px;
}

.day-content {
  padding: 20px;
  background-color: white;
}

.time-section {
  margin-bottom: 15px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-weight: 600;
  color: rgb(1, 128, 165);
  font-size: 14px;
}

.time-period-item {
  margin-bottom: 15px;
}

.time-period-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

.empty-state {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 20px 0;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px dashed #ddd;
}

.error-text {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 5px;
}

.delete-icon-button {
  color: #714B67 !important;
  padding: 6px !important;
  transition: all 0.2s ease;
}

.delete-icon-button:hover {
  color: #922575 !important;
  background-color: #f1edf0 !important;
  border-radius: 4px;
}

/* 表格相关样式 */
.work-time-table {
  border-radius: 5px;
  overflow: hidden;
}

.expand-content {
  background-color: #f8f9fa;
  padding: 20px;
  margin: 10px 0;
  border-radius: 5px;
  border: 1px solid #e9ecef;
}

.empty-text {
  color: #999999;
  font-style: italic;
}

</style>